package com.infindo.frame.data.net;


import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Random;
import java.util.Vector;
import java.util.zip.GZIPInputStream;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;

import android.content.Context;
import android.util.Log;
import android.webkit.WebView;

import com.infindo.frame.data.DataHandler;
import com.infindo.frame.data.DataProcessor;
import com.infindo.frame.util.Base64;
import com.infindo.frame.util.InputStreamProvider;
import com.infindo.frame.util.StringUtil;




 

public class RequestTwitterPost extends DataHandler {

	
	public static final int GZIP_MAGIC = 0x1f8b;

	private static final String MAC_NAME = "HmacSHA1";

	private DataProcessor dataProc;
	private String type;
	private String tokenUrl = "http://twitter.com/oauth/request_token";
	private String authorizeUrl = "http://twitter.com/oauth/authorize";
	private String postUrl = "https://api.twitter.com/1/statuses/update.json";
	private String logoutUrl = "http://twitter.com/logout";

	private int site;
	private boolean isTransLocation;
	//		private String content = "&session%5Busername_or_email%5D=email2chenxi%40gmail.com&session%5Bpassword%5D=7654321";
	private String content;
	private int currentView = 0;
	private String token;
	private String authenticity_token;
	private String oauth_token;
	private String post_authenticity_token;

	private String updateStatus="";
	private String userName;
	private String password;
	private String text;

	private String k;
	private String guest_id;
	private String _twitter_sess;
	private String auth_token;
	private String twid;
	private String twll;
	private String original_referer;
	private String lang;
	private String ab_ess = " ab_sess_promoted_arrows_and_pills_78=1";
	
	private String logoutToken = "authenticity_token=146f03c509670cde3ebf68b9672aaa6a5e1f35da&redirect=false";

    private String GZIP = "gzip";
    
    private Context context;

	public String getLogoutToken() {
		return logoutToken;
	}

	public void setLogoutToken(String token) {
		this.logoutToken = "authenticity_token="+token+"&redirect=false";;
	}

	public String getUpdateStatus() {
		return updateStatus;
	}

	public void setUpdateStatus(String text,String token) {
		//			this.updateStatus = "include_entities=true&status=Test+434+Malaysia+update+status.&post_authenticity_token="+token;
		try {
			text = URLEncoder.encode(text, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.updateStatus = "include_entities=true&status="+text+"&post_authenticity_token="+token;//5b29670c9aa81bca8dc0286392db791b119d4ae6";
	}

	public RequestTwitterPost(Context context,String userName,String password,String text,String type,int site,boolean isNeedTimer,DataProcessor dataProc,int dataHandlerNo,CallbackListener listener)
	{
		super(dataHandlerNo,listener);
		this.setBolNeedTimer(isNeedTimer);
		this.userName = userName;
		this.password = password;
		this.text = text;
        this.context = context;
		this.type = type;
		this.site = site;
		this.dataProc = dataProc;
//		Log.e("user_agent","userAgent:"+new WebView(context).getSettings().getUserAgentString());
	}

	public void start()
	{
		new Thread(this).start();
	}

	public void run()
	{	
		NameValuePair nvp;
		Vector vect = new Vector();
		nvp = new NameValuePair("session[username_or_email]",userName);
		vect.addElement(nvp);
		nvp = new NameValuePair("session[password]",password);
		vect.addElement(nvp);

		StringBuffer link = new StringBuffer();
		for(int i=0;i<vect.size();i++){
			nvp = (NameValuePair)vect.elementAt(i);
			String name = StringUtil.checkUrl(nvp.getName());
			String password =StringUtil.checkUrl( nvp.getValue());
			link.append("&"+name+"="+password);
		}
		content = link.toString();

		isTransLocation = false;
		Object result = null;
		switch(currentView){
		case 0:
			result = token(tokenUrl);
			if(isTransLocation){
				start();
				return;
			}
			if(result==null){
				if (this.dataProc.checkNoCancelQueue(super.getDataHandlerNo()))
					this.getCallbackListener().callback(type, site,result);
				break;
			}
			currentView = 1;
			start();
			break;
		case 1:
			result = authorize(authorizeUrl,token);
			if(isTransLocation){
				start();
				return ;
			}
			if(result==null){
				if (this.dataProc.checkNoCancelQueue(super.getDataHandlerNo()))
					this.getCallbackListener().callback(type, site,result);
				break;
			}
			currentView = 2;
			start();
			break;
		case 2:
			result = post(postUrl,updateStatus);
			if(isTransLocation){
				start();
				return ;
			}
			if(result == null){
			if (this.dataProc.checkNoCancelQueue(super.getDataHandlerNo()))
				this.getCallbackListener().callback(type, site,result);
			break;
			}
			currentView = 3;
			start();
			break;
		case 3:
			result = logout(logoutUrl,logoutToken);
			if(isTransLocation){
				start();
				return;
			}
			if (this.dataProc.checkNoCancelQueue(super.getDataHandlerNo()))
				this.getCallbackListener().callback(type, site,result);
		}
	}

	protected String generateTimestamp() {
		return Long.toString(System.currentTimeMillis() / 1000L);
	}

	protected String generateNonce() {
		return Long.toString(new Random().nextLong());
	}

	protected String generateKey(String param){

		try{
			String keyString = "8AqzeDY64nXGZv4ZVeztOpvZlv3f8pbPxplNEAYo4&";
//			System.out.println("keyString:"+keyString);
			byte[] keyBytes = keyString.getBytes("UTF-8");

//			HMACKey key = new HMACKey(keyBytes);
//
//			HMAC mac = new HMAC(key, new SHA1Digest());

            SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
           
            Mac mac = Mac.getInstance(MAC_NAME);
            mac.init(key);

			String sbs = param;
 
			byte[] text = sbs.getBytes("UTF-8");
 
			String sign = Base64.encode(mac.doFinal(text)).trim();
			sign = URLEncoder.encode(sign, "UTF-8");
			sign = checkEquals(sign);
//			System.out.println("sign:"+sign);
			return sign;
		}catch(Exception e){
			System.out.println("generateKey:error:"+e.getMessage());
		}
		return "";
	}

	private String checkEquals(String sign){
		int size = sign.length();
		int index = 0;
		char[] tempChar = sign.toCharArray();
		StringBuffer sb = new StringBuffer();
		while(index<size){
			if(tempChar[index]=='='){
				sb.append("%3D");
			}else{
				sb.append(tempChar[index]);
			}
			index++;
		}
		return sb.toString();
	}


	public synchronized Object token(String url){
		HttpURLConnection hcon = null;
		StringBuffer message = new StringBuffer();
		DataOutputStream dos = null;
		DataInputStream dis = null;
		InputStream is = null;
		InputStreamReader isr = null;
		try {
//			System.out.println("************************ token **********************************");
//			System.out.println("url:"+url);
			URL myUrl = new URL(url);
			hcon = (HttpURLConnection)myUrl.openConnection();
			hcon.setDoInput(true);
			hcon.setDoOutput(true);
			hcon.setRequestMethod("POST");
			hcon.setRequestProperty("Accept","*/*");
			hcon.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; CIBA; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
			hcon.setRequestProperty("Connection", "keep-alive");
			hcon.setRequestProperty("Cache-Control", "no-cache");
			String timeStamp = generateTimestamp();
			String nonce = generateNonce();
			String params = "POST&http%3A%2F%2Ftwitter.com%2Foauth%2Frequest_token&oauth_callback%3D%26oauth_consumer_key%3DVGhITevEakG8QHmuKMCQg%26oauth_nonce%3D"+nonce+"%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D"+timeStamp+"%26oauth_version%3D1.0";
			String signature = generateKey(params);
//			System.out.println("signature:"+signature);
//			System.out.println("signature.length:"+signature.length());
			String value = "OAuth oauth_callback=\"\",oauth_consumer_key=\"VGhITevEakG8QHmuKMCQg\",oauth_version=\"1.0\", oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\""+timeStamp+"\", oauth_nonce=\""+nonce+"\", oauth_signature=\""+signature+"\"";
			hcon.setRequestProperty("Authorization", value);
			hcon.setRequestProperty("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
			//	hcon.setRequestProperty("X-UserAgent", "plaf=bb/ver=1.0/icon="+MenuScreen.ImageW+"/width="+Const.SCW+"/lan=en");
			//				dos = hcon.openDataOutputStream();
//			System.out.println("Authorization:"+value);

			this.startConnect();
			this.dataProc.getDataTimer().addConnect(this);

			int code = hcon.getResponseCode();
//			System.out.println(code); 
			for(int i=0;i<25;i++){
//				System.out.println("HeaderField:"+i+":"+hcon.getHeaderFieldKey(i)+":"+hcon.getHeaderField(i));
				if(hcon.getHeaderField(i)==null)
					continue;

			}


			
			if(code!= 200){
				if( code == 301 || code == 302)
				{
					url = hcon.getHeaderField("Location");
					if(url==null)
					{
						return null;
					}
					try {
						if (hcon != null)
							hcon.disconnect();
					} catch (Exception ignored) {}
					this.tokenUrl = url;
					isTransLocation = true;
				}
				return null;
			}

			dis = new DataInputStream(hcon.getInputStream());

			isr = new InputStreamReader(dis, "UTF-8");

			int ch;
			while ((ch = isr.read()) != -1) {
				message = message.append((char) ch);
			}
		}catch(UnknownHostException ue){
//			System.out.println("*******message end error:*********" + ue.getMessage()); 
			return null;
		} catch (Exception e) {
//			System.out.println("*******message end error:*********" + e.getMessage()); 
			e.printStackTrace();
			return null;
		} finally {

			if (hcon != null)
				try {
					hcon.disconnect();
				} catch (Exception e) {}
				if (dis != null)
					try {
						dis.close();
					} catch (IOException e) {}

		}
		if (message!= null) {
			try {
				String s = message.toString();
				int start = s.indexOf("oauth_token");
				int end = s.indexOf("&");
				if(start!=-1&&end!=-1){
					oauth_token = s.substring(start,end+1);
					s = s.substring(end+1);
				}
				start = s.indexOf("oauth_token_secret");
				end = s.indexOf("&");
				if(start!=-1&&end!=-1){
					authenticity_token = "authenticity_token"+s.substring(start+18,end);
					s = s.substring(end+1);
				}

				token = authenticity_token+"&"+oauth_token+content;
//				System.out.println("message:"+message.toString());
				return message.toString();
			} catch (Exception e) {

//				System.out.println("*******message end error:*********" + e.getMessage());
				return null;
			}
		}
		return null;
	}



	public synchronized Object authorize(String url ,String data){
		HttpURLConnection hcon = null;
		StringBuffer message = new StringBuffer();
		DataOutputStream dos = null;
		DataInputStream dis = null;
		InputStream is = null;
		OutputStream out = null;
		InputStreamReader isr = null;
		try {
//			System.out.println("************************ authorize **********************************");
//			System.out.println("authorize content:"+data);
//			System.out.println("url:"+url);
			byte[] authorizeData = data.getBytes("UTF-8");
			URL myUrl = new URL(url);
			hcon = (HttpURLConnection)myUrl.openConnection();
			hcon.setRequestMethod("POST");
            hcon.setDoInput(true);
            hcon.setDoOutput(true);
			hcon.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
			hcon.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			hcon.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
			hcon.setRequestProperty("Accept-Encoding", GZIP);		
			hcon.setRequestProperty("Accept-Charset","GB2312,utf-8;q=0.7,*;q=0.7");
			hcon.setRequestProperty("Keep-Alive","115");
			hcon.setRequestProperty("Connection","keep-alive");
			hcon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			hcon.setRequestProperty("Content-Length",""+authorizeData.length);

			out = hcon.getOutputStream();
			out.write(authorizeData);
			out.flush();
			out.close();


			this.startConnect();
			this.dataProc.getDataTimer().addConnect(this);

			/*	byte[] byteRequest = content.getBytes();
				for (int i = 0; i < byteRequest.length; i++) {
					dos.writeByte(byteRequest[i]);
				}
				dos.flush();*/
			int code = hcon.getResponseCode();
//            System.out.println("code:"+code);
			for(int i=0;i<35;i++){
//				Log.e("handler--1","HeaderField:"+i+":"+hcon.getHeaderFieldKey(i)+":"+hcon.getHeaderField(i));
				if(hcon.getHeaderField(i)==null)
					continue;
				int site = hcon.getHeaderField(i).indexOf("k=");
				if(site!=-1){
					k = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("guest_id=");
				if(site!=-1){
					guest_id = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("_twitter_sess=");
				if(site!=-1){
					_twitter_sess = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("auth_token=");
				if(site!=-1){
					auth_token = getCookie(hcon.getHeaderField(i));
					setLogoutToken(auth_token);
				}
				site = hcon.getHeaderField(i).indexOf("twid=");
				if(site!=-1){
					twid = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("twll=");
				if(site!=-1){
					twll = getCookie(hcon.getHeaderField(i));
				}
				site = hcon.getHeaderField(i).indexOf("original_referer=");
				if(site!=-1){
					original_referer = getCookie(hcon.getHeaderField(i));
				}else{
					original_referer = "original_referer=; ";
				}
				site = hcon.getHeaderField(i).indexOf("lang=");
				if(site!=-1){
					lang = getCookie(hcon.getHeaderField(i));
				}else{
					lang = "lang=en; ";
				}

			}

 
			if(code!= 200){
				if( code == 301 || code == 302)
				{
					url = hcon.getHeaderField("Location");
					if(url==null)
					{
						return null;
					}
					try {
						if (hcon != null)
							hcon.disconnect();
					} catch (Exception ignored) {}
					this.tokenUrl = url;
					isTransLocation = true;
				}
				return null;
			}

			//				dis = new DataInputStream(hcon.openInputStream());
			//				isr = new InputStreamReader(dis, "UTF-8");
//			int magic = InputStreamProvider.getMagicNumber(hcon.getInputStream());
//			System.out.println("magic:"+magic+"?="+ GZIP_MAGIC);
		 
			is = hcon.getInputStream();
			int size = hcon.getContentLength();
//			  System.out.println("size:"+size);
	          int t1 = is.read();
	//	          System.out.println("t1:"+t1);
//	          Log.e("t1:", t1+"");
	          if (t1 < 0) throw new EOFException("Failed to read magic number");
	          int magic = (t1 & 0xff) << 8;
//	          Log.e("magic1:", magic+"");
	//	          System.out.println("magic1:"+magic);
	          int t2 = is.read();
//	          Log.e("t2:", t2+"");
	//	          System.out.println("t2:"+t2);
	          if (t2 < 0) throw new EOFException("Failed to read magic number");
	          magic += t2 & 0xff;
	//	          System.out.println("magic2:"+magic);
//	          Log.e("magic2", magic+"");
	           if(magic==GZIP_MAGIC){
	          
	//				is = hcon.getInputStream();
					size = is.available()+2;
//					System.out.println("size:"+size);
					byte[] temps = new byte[size];
	//				int offset = 0;
	//				InputStreamProvider.appendInt(temps, offset, 31);
	//				offset+=4;
	//				InputStreamProvider.appendInt(temps, offset, 139);
	//				offset+=4;
					temps[0] = 0x1f;
					temps[1] = (byte)0x8b;
					is.read(temps, 2, size-2);
//					System.out.println("2 here now...1");
					ByteArrayInputStream bais = new ByteArrayInputStream(temps);
//					System.out.println("2 here now...2");
					GZIPInputStream gzipin = new GZIPInputStream(bais);
//					System.out.println("2 here now...3");
					isr = new InputStreamReader(gzipin,"UTF-8");
	           }else{
					byte[] temps = new byte[size];
//					int offset = 0;
//					InputStreamProvider.appendInt(temps, offset, 31);
//					offset+=4;
//					InputStreamProvider.appendInt(temps, offset, 139);
//					offset+=4;
//					temps[0] = 0x1f;
//					temps[1] = (byte)0x8b;
					temps[0] = (byte)t1;
					temps[1] = (byte)t2;
					is.read(temps, 2, size-2);
					ByteArrayInputStream bais = new ByteArrayInputStream(temps);
//					GZIPInputStream gzipin = new GZIPInputStream(bais);
//					InputStream iss = new InputStream();
					isr = new InputStreamReader(bais,"UTF-8");
					
					
	           }
			 
			int ch;
			while ((ch = isr.read()) != -1) {
				message = message.append((char) ch);
			}
			//		        byte[] buffer;
			//		    	is = hc.openInputStream();
			//				if (is == null) {
			//					return null;
			//				}
			//
			//				    int count = 0;
			//					int ret=-1;
			//			        byte[] data = new byte[1024];
			//			        // read
			//			        while( (ret = is.read()) != -1)
			//			        {
			//			            if(count == data.length) {
			//			                data = addCapacity(data);
			//			            }
			//			            data[count++] = (byte) ret;
			//			        }
			//			        buffer = new byte[count];
			//			        System.arraycopy(data,0,buffer,0,count);
			//			        data = null;
			//			    String s = message.toString();
			//			    System.out.println(s);
		} catch (Exception e) {
//			System.out.println("*******message end error:*********" + e.getMessage()); 
			e.printStackTrace();
			return null;
		} finally {

			if (hcon != null)
				try {
					hcon.disconnect();
				} catch (Exception e) {}
				if (dis != null)
					try {
						dis.close();
					} catch (IOException e) {}

		}
		if (message!= null) {
			try {
				String s = message.toString();
//				System.out.println(s.length()+"  message:"+s);
				int index = s.indexOf("twttr.form_authenticity_token");
				if(index!=-1){
					s = s.substring(index);
					index = s.indexOf("'");
					if(index!=-1){
						post_authenticity_token = s.substring(index+1);
						index = post_authenticity_token.indexOf("'");
						if(index!=-1){
							post_authenticity_token = post_authenticity_token.substring(0,index);
						}
					}
				}
				setUpdateStatus(text,post_authenticity_token);
				return message.toString();
			} catch (Exception e) {

//				System.out.println("*******message end error:*********" + e.getMessage());
				return null;
			}
		}
		return null;
	}



	public synchronized Object post(String url ,String data){
		HttpsURLConnection hcon = null;
		StringBuffer message = new StringBuffer();
		DataOutputStream dos = null;
		DataInputStream dis = null;
		InputStream is = null;
		OutputStream out = null;
		InputStreamReader isr = null;
		try {
//			System.out.println("************************ post **********************************");
//			System.out.println("post content:"+data);
//			System.out.println("url:"+url);
			byte[] postData = data.getBytes("UTF-8");
			URL myUrl = new URL(url);
			hcon = (HttpsURLConnection)myUrl.openConnection();
			hcon.setRequestMethod("POST");
            hcon.setDoInput(true);
            hcon.setDoOutput(true);
			hcon.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
			hcon.setRequestProperty("Accept","application/json, text/javascript, */*; q=0.01");
			hcon.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
			hcon.setRequestProperty("Accept-Encoding",GZIP);
			hcon.setRequestProperty("Accept-Charset","GB2312,utf-8;q=0.7,*;q=0.7");
			hcon.setRequestProperty("Keep-Alive","115");
			hcon.setRequestProperty("Connection","keep-alive");
			hcon.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
			hcon.setRequestProperty("X-Phx","true");
			hcon.setRequestProperty("X-Requested-With","XMLHttpRequest");
			hcon.setRequestProperty("Referer","https://api.twitter.com/receiver.html");

			//				hcon.setRequestProperty("Cookie","k=211.25.194.234.1310528158039489; guest_id=v1%3A131052815806634351; _twitter_sess=BAh7DzoTc2hvd19oZWxwX2xpbmswOhVpbl9uZXdfdXNlcl9mbG93MDoJdXNl%250AcmkDMF3rOhBzdGF5X3NlY3VyZVQ6D2NyZWF0ZWRfYXRsKwh2uZAhMQE6G3Nl%250Ac3Npb25fcGFzc3dvcmRfdG9rZW4iLWVhOGI4Mjc4OGU5OTFlMDQyMzkxZGMw%250AZWFlNjFlMTE5ODRlMzU4YTY6B2lkIiUyOTNjNzA3YzYxMjEyZTM2NDM5N2Y1%250AYzAwMmQ5YWMyMzoMY3NyZl9pZCIlMTExZDRkODgyNjlhMzAzZGI1ZGQ3MWI2%250AMzhkMDQ0ZWM6E3Bhc3N3b3JkX3Rva2VuIi1lYThiODI3ODhlOTkxZTA0MjM5%250AMWRjMGVhZTYxZTExOTg0ZTM1OGE2IgpmbGFzaElDOidBY3Rpb25Db250cm9s%250AbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--36601bcdced1355aae66ca2968427c82a440688d; __utma=43838368.196425278.1310528164.1310528164.1310528164.1; __utmb=43838368.2.10.1310528164; __utmc=43838368; __utmz=43838368.1310528164.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ab_sess_homepage_designs-51=1; auth_token=ea8b82788e991e042391dc0eae61e11984e358a6; secure_session=true; twid=u%3D15424816%7CEOiyqRbiJO%2BNfTAV18PS%2BsoQbbE%3D; twll=l%3D1310528209; original_referer=padhuUp37zigs9eJTisr5PnVtwPa2Ks3aYGytRQKC2hhgexXtH6h6g%3D%3D; lang=en; ab_sess_promoted_arrows_and_pills_78=1");
			//				String cook = "k=211.25.194.234.1310542234948222; guest_id=v1%3A131054223495826837; __utma=43838368.1872628168.1310542248.1310542332.1310554938.3; __utmz=43838368.1310542248.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmv=43838368.lang%3A%20en; twll=l%3D1310556086; _twitter_sess=BAh7DjoTc2hvd19oZWxwX2xpbmswOhVpbl9uZXdfdXNlcl9mbG93MDoOcmV0%250AdXJuX3RvIgGQaHR0cDovL3R3aXR0ZXIuY29tL3JhamFsYXdha2FzdHJvP29h%250AdXRoX3Rva2VuPWpDNlQ3bzhVQVpPVTRFaWtJM2NBRmswTTZjUUhtMmNzOWFh%250AS0wzdlZzMCZvYXV0aF92ZXJpZmllcj1aNGpUZThkNVVWb0k0ZHFLMHZic0E1%250AY1pQQzE5S2gwemdiRWM0WjZjOgl1c2VyaQMwXes6D2NyZWF0ZWRfYXRsKwjI%250AUCkjMQE6B2lkIiU3ZWEzZDI3MjRkYTljYmNlNTVmMDk1Y2U2ZDE5NzNhYToM%250AY3NyZl9pZCIlMWFiZTkyMTllOTZlMmM1ZDM5ZjljZWYxMDVjYzRmNmI6E3Bh%250Ac3N3b3JkX3Rva2VuIi1lYThiODI3ODhlOTkxZTA0MjM5MWRjMGVhZTYxZTEx%250AOTg0ZTM1OGE2IgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6%250ARmxhc2hIYXNoewAGOgpAdXNlZHsA--360cc1c0a0deea42093e90cf8837338082d8c1ba; __utmb=43838368.6.10.1310554938; __utmc=43838368; original_referer=JbKFAfGwv4RwApvTLqS%2BuSg2nN6n6Sc2FNg%2B%2FJZdApHOHiilCO8gnQ%3D%3D; auth_token=ea8b82788e991e042391dc0eae61e11984e358a6; twid=u%3D15424816%7CEOiyqRbiJO%2BNfTAV18PS%2BsoQbbE%3D; lang=en; ab_sess_promoted_arrows_and_pills_78=1";
			//				hcon.setRequestProperty("Cookie",cook);
			//				String cook = "k=211.25.194.234.1310542234948222; guest_id=v1%3A131054223495826837; _twitter_sess=BAh7DjoTc2hvd19oZWxwX2xpbmswOhVpbl9uZXdfdXNlcl9mbG93MDoOcmV0%250AdXJuX3RvIgGQaHR0cDovL3R3aXR0ZXIuY29tL3JhamFsYXdha2FzdHJvP29h%250AdXRoX3Rva2VuPWpDNlQ3bzhVQVpPVTRFaWtJM2NBRmswTTZjUUhtMmNzOWFh%250AS0wzdlZzMCZvYXV0aF92ZXJpZmllcj1aNGpUZThkNVVWb0k0ZHFLMHZic0E1%250AY1pQQzE5S2gwemdiRWM0WjZjOgl1c2VyaQMwXes6D2NyZWF0ZWRfYXRsKwjI%250AUCkjMQE6B2lkIiU3ZWEzZDI3MjRkYTljYmNlNTVmMDk1Y2U2ZDE5NzNhYToM%250AY3NyZl9pZCIlMWFiZTkyMTllOTZlMmM1ZDM5ZjljZWYxMDVjYzRmNmI6E3Bh%250Ac3N3b3JkX3Rva2VuIi1lYThiODI3ODhlOTkxZTA0MjM5MWRjMGVhZTYxZTEx%250AOTg0ZTM1OGE2IgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6%250ARmxhc2hIYXNoewAGOgpAdXNlZHsA--360cc1c0a0deea42093e90cf8837338082d8c1ba; original_referer=JbKFAfGwv4RwApvTLqS%2BuSg2nN6n6Sc2FNg%2B%2FJZdApHOHiilCO8gnQ%3D%3D; auth_token=ea8b82788e991e042391dc0eae61e11984e358a6; twid=u%3D15424816%7CEOiyqRbiJO%2BNfTAV18PS%2BsoQbbE%3D; lang=en; ab_sess_promoted_arrows_and_pills_78=1";
			String cook = 	k+guest_id+_twitter_sess+auth_token+twid+twll+original_referer+lang+ab_ess;

			hcon.setRequestProperty("Cookie",cook);
//			System.out.println("post cookie:"+cook);

			hcon.setRequestProperty("Pragma","no-cache");
			hcon.setRequestProperty("Cache-Control","no-cache");
			hcon.setRequestProperty("Content-Length",""+postData.length);

			out = hcon.getOutputStream();
			out.write(postData);
			out.flush();
			out.close();


			this.startConnect();
			this.dataProc.getDataTimer().addConnect(this);

			/*	byte[] byteRequest = content.getBytes();
				for (int i = 0; i < byteRequest.length; i++) {
					dos.writeByte(byteRequest[i]);
				}
				dos.flush();*/
			int code = hcon.getResponseCode();
			for(int i=0;i<25;i++){
//				System.out.println("HeaderField:"+i+":"+hcon.getHeaderFieldKey(i)+":"+hcon.getHeaderField(i));
				if(hcon.getHeaderField(i)==null)
					continue;

			}

//			System.out.println(code); 
			if(code!= 200){
				if( code == 301 || code == 302)
				{
					url = hcon.getHeaderField("Location");
					if(url==null)
					{
						return null;
					}
					try {
						if (hcon != null)
							hcon.disconnect();
					} catch (Exception ignored) {}
					this.postUrl = url;
					isTransLocation = true;
				}
				return null;
			}

//							dis = new DataInputStream(hcon.openInputStream());
//							isr = new InputStreamReader(dis, "UTF-8");
			GZIPInputStream gzipin = new GZIPInputStream(hcon.getInputStream());
			isr = new InputStreamReader(gzipin,"UTF-8");

			int ch;
			while ((ch = isr.read()) != -1) {
				message = message.append((char) ch);
			}
			//		        byte[] buffer;
			//		    	is = hc.openInputStream();
			//				if (is == null) {
			//					return null;
			//				}
			//
			//				    int count = 0;
			//					int ret=-1;
			//			        byte[] data = new byte[1024];
			//			        // read
			//			        while( (ret = is.read()) != -1)
			//			        {
			//			            if(count == data.length) {
			//			                data = addCapacity(data);
			//			            }
			//			            data[count++] = (byte) ret;
			//			        }
			//			        buffer = new byte[count];
			//			        System.arraycopy(data,0,buffer,0,count);
			//			        data = null;
			//			    String s = message.toString();
			//			    System.out.println(s);
		} catch (Exception e) {
//			System.out.println("*******message end error:*********" + e.getMessage()); 
			e.printStackTrace();
			return null;
		} finally {

			if (hcon != null)
				try {
					hcon.disconnect();
				} catch (Exception e) {}
				if (dis != null)
					try {
						dis.close();
					} catch (IOException e) {}

		}
		if (message!= null) {
			try {
				String s = message.toString();
//				System.out.println("message:"+s);
//				Log.e("zxb-message", s);
				int index = s.indexOf("user");
				if(index!=-1){
					return "ok";
				}else{
					return "fail";
				}
				
			//	return message.toString();
			} catch (Exception e) {

//				System.out.println("*******message end error:*********" + e.getMessage());
				return null;
			}
		}
		return null;
	}
	
	

	public synchronized Object logout(String url ,String data){
		HttpURLConnection hcon = null;
		StringBuffer message = new StringBuffer();
		DataOutputStream dos = null;
		DataInputStream dis = null;
		InputStream is = null;
		OutputStream out = null;
		InputStreamReader isr = null;
		try {
//			System.out.println("************************ logout **********************************");
//			System.out.println("post content:"+data);
//			System.out.println("url:"+url);
			byte[] postData = data.getBytes("UTF-8");
			URL myUrl = new URL(url);
			hcon = (HttpURLConnection)myUrl.openConnection();
			hcon.setRequestMethod("POST");
            hcon.setDoInput(true);
            hcon.setDoOutput(true);
			hcon.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13");
			hcon.setRequestProperty("Accept","application/json, text/javascript, */*; q=0.01");
			hcon.setRequestProperty("Accept-Language","zh-cn,zh;q=0.5");
			hcon.setRequestProperty("Accept-Encoding",GZIP);
			hcon.setRequestProperty("Accept-Charset","GB2312,utf-8;q=0.7,*;q=0.7");
			hcon.setRequestProperty("Keep-Alive","115");
			hcon.setRequestProperty("Proxy-Connection","keep-alive");
			hcon.setRequestProperty("Connection","keep-alive");
			hcon.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
			hcon.setRequestProperty("X-Phx","true");
			hcon.setRequestProperty("X-Requested-With","XMLHttpRequest");
			hcon.setRequestProperty("Referer","http://twitter.com/");

			//				hcon.setRequestProperty("Cookie","k=211.25.194.234.1310528158039489; guest_id=v1%3A131052815806634351; _twitter_sess=BAh7DzoTc2hvd19oZWxwX2xpbmswOhVpbl9uZXdfdXNlcl9mbG93MDoJdXNl%250AcmkDMF3rOhBzdGF5X3NlY3VyZVQ6D2NyZWF0ZWRfYXRsKwh2uZAhMQE6G3Nl%250Ac3Npb25fcGFzc3dvcmRfdG9rZW4iLWVhOGI4Mjc4OGU5OTFlMDQyMzkxZGMw%250AZWFlNjFlMTE5ODRlMzU4YTY6B2lkIiUyOTNjNzA3YzYxMjEyZTM2NDM5N2Y1%250AYzAwMmQ5YWMyMzoMY3NyZl9pZCIlMTExZDRkODgyNjlhMzAzZGI1ZGQ3MWI2%250AMzhkMDQ0ZWM6E3Bhc3N3b3JkX3Rva2VuIi1lYThiODI3ODhlOTkxZTA0MjM5%250AMWRjMGVhZTYxZTExOTg0ZTM1OGE2IgpmbGFzaElDOidBY3Rpb25Db250cm9s%250AbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--36601bcdced1355aae66ca2968427c82a440688d; __utma=43838368.196425278.1310528164.1310528164.1310528164.1; __utmb=43838368.2.10.1310528164; __utmc=43838368; __utmz=43838368.1310528164.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ab_sess_homepage_designs-51=1; auth_token=ea8b82788e991e042391dc0eae61e11984e358a6; secure_session=true; twid=u%3D15424816%7CEOiyqRbiJO%2BNfTAV18PS%2BsoQbbE%3D; twll=l%3D1310528209; original_referer=padhuUp37zigs9eJTisr5PnVtwPa2Ks3aYGytRQKC2hhgexXtH6h6g%3D%3D; lang=en; ab_sess_promoted_arrows_and_pills_78=1");
			//				String cook = "k=211.25.194.234.1310542234948222; guest_id=v1%3A131054223495826837; __utma=43838368.1872628168.1310542248.1310542332.1310554938.3; __utmz=43838368.1310542248.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmv=43838368.lang%3A%20en; twll=l%3D1310556086; _twitter_sess=BAh7DjoTc2hvd19oZWxwX2xpbmswOhVpbl9uZXdfdXNlcl9mbG93MDoOcmV0%250AdXJuX3RvIgGQaHR0cDovL3R3aXR0ZXIuY29tL3JhamFsYXdha2FzdHJvP29h%250AdXRoX3Rva2VuPWpDNlQ3bzhVQVpPVTRFaWtJM2NBRmswTTZjUUhtMmNzOWFh%250AS0wzdlZzMCZvYXV0aF92ZXJpZmllcj1aNGpUZThkNVVWb0k0ZHFLMHZic0E1%250AY1pQQzE5S2gwemdiRWM0WjZjOgl1c2VyaQMwXes6D2NyZWF0ZWRfYXRsKwjI%250AUCkjMQE6B2lkIiU3ZWEzZDI3MjRkYTljYmNlNTVmMDk1Y2U2ZDE5NzNhYToM%250AY3NyZl9pZCIlMWFiZTkyMTllOTZlMmM1ZDM5ZjljZWYxMDVjYzRmNmI6E3Bh%250Ac3N3b3JkX3Rva2VuIi1lYThiODI3ODhlOTkxZTA0MjM5MWRjMGVhZTYxZTEx%250AOTg0ZTM1OGE2IgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6%250ARmxhc2hIYXNoewAGOgpAdXNlZHsA--360cc1c0a0deea42093e90cf8837338082d8c1ba; __utmb=43838368.6.10.1310554938; __utmc=43838368; original_referer=JbKFAfGwv4RwApvTLqS%2BuSg2nN6n6Sc2FNg%2B%2FJZdApHOHiilCO8gnQ%3D%3D; auth_token=ea8b82788e991e042391dc0eae61e11984e358a6; twid=u%3D15424816%7CEOiyqRbiJO%2BNfTAV18PS%2BsoQbbE%3D; lang=en; ab_sess_promoted_arrows_and_pills_78=1";
			//				hcon.setRequestProperty("Cookie",cook);
			//				String cook = "k=211.25.194.234.1310542234948222; guest_id=v1%3A131054223495826837; _twitter_sess=BAh7DjoTc2hvd19oZWxwX2xpbmswOhVpbl9uZXdfdXNlcl9mbG93MDoOcmV0%250AdXJuX3RvIgGQaHR0cDovL3R3aXR0ZXIuY29tL3JhamFsYXdha2FzdHJvP29h%250AdXRoX3Rva2VuPWpDNlQ3bzhVQVpPVTRFaWtJM2NBRmswTTZjUUhtMmNzOWFh%250AS0wzdlZzMCZvYXV0aF92ZXJpZmllcj1aNGpUZThkNVVWb0k0ZHFLMHZic0E1%250AY1pQQzE5S2gwemdiRWM0WjZjOgl1c2VyaQMwXes6D2NyZWF0ZWRfYXRsKwjI%250AUCkjMQE6B2lkIiU3ZWEzZDI3MjRkYTljYmNlNTVmMDk1Y2U2ZDE5NzNhYToM%250AY3NyZl9pZCIlMWFiZTkyMTllOTZlMmM1ZDM5ZjljZWYxMDVjYzRmNmI6E3Bh%250Ac3N3b3JkX3Rva2VuIi1lYThiODI3ODhlOTkxZTA0MjM5MWRjMGVhZTYxZTEx%250AOTg0ZTM1OGE2IgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6%250ARmxhc2hIYXNoewAGOgpAdXNlZHsA--360cc1c0a0deea42093e90cf8837338082d8c1ba; original_referer=JbKFAfGwv4RwApvTLqS%2BuSg2nN6n6Sc2FNg%2B%2FJZdApHOHiilCO8gnQ%3D%3D; auth_token=ea8b82788e991e042391dc0eae61e11984e358a6; twid=u%3D15424816%7CEOiyqRbiJO%2BNfTAV18PS%2BsoQbbE%3D; lang=en; ab_sess_promoted_arrows_and_pills_78=1";
			String cook = 	k+guest_id+_twitter_sess+auth_token+twid+twll+original_referer+lang+ab_ess;

			hcon.setRequestProperty("Cookie",cook);
//			System.out.println("post cookie:"+cook);

			hcon.setRequestProperty("Pragma","no-cache");
			hcon.setRequestProperty("Cache-Control","no-cache");
			hcon.setRequestProperty("Content-Length",""+postData.length);

			out = hcon.getOutputStream();
			out.write(postData);
			out.flush();
			out.close();


			this.startConnect();
			this.dataProc.getDataTimer().addConnect(this);

			/*	byte[] byteRequest = content.getBytes();
				for (int i = 0; i < byteRequest.length; i++) {
					dos.writeByte(byteRequest[i]);
				}
				dos.flush();*/
			int code = hcon.getResponseCode();
			for(int i=0;i<25;i++){
//				System.out.println("HeaderField:"+i+":"+hcon.getHeaderFieldKey(i)+":"+hcon.getHeaderField(i));
				if(hcon.getHeaderField(i)==null)
					continue;

			}

//			System.out.println(code); 
			if(code!= 200){
				if( code == 301 || code == 302)
				{
					url = hcon.getHeaderField("Location");
					if(url==null)
					{
						return null;
					}
					try {
						if (hcon != null)
							hcon.disconnect();
					} catch (Exception ignored) {}
					this.postUrl = url;
					isTransLocation = true;
				}
				return null;
			}

//							dis = new DataInputStream(hcon.openInputStream());
//							isr = new InputStreamReader(dis, "UTF-8");
//			GZIPInputStream gzipin = new GZIPInputStream(hcon.getInputStream());
			is = hcon.getInputStream();
			isr = new InputStreamReader(is,"UTF-8");

			int ch;
			while ((ch = isr.read()) != -1) {
				message = message.append((char) ch);
			}
			//		        byte[] buffer;
			//		    	is = hc.openInputStream();
			//				if (is == null) {
			//					return null;
			//				}
			//
			//				    int count = 0;
			//					int ret=-1;
			//			        byte[] data = new byte[1024];
			//			        // read
			//			        while( (ret = is.read()) != -1)
			//			        {
			//			            if(count == data.length) {
			//			                data = addCapacity(data);
			//			            }
			//			            data[count++] = (byte) ret;
			//			        }
			//			        buffer = new byte[count];
			//			        System.arraycopy(data,0,buffer,0,count);
			//			        data = null;
			//			    String s = message.toString();
			//			    System.out.println(s);
		} catch (Exception e) {
//			System.out.println("*******message end error:*********" + e.getMessage()); 
			e.printStackTrace();
			return null;
		} finally {

			if (hcon != null)
				try {
					hcon.disconnect();
				} catch (Exception e) {}
				if (dis != null)
					try {
						dis.close();
					} catch (IOException e) {}

		}
		if (message!= null) {
			try {
				String s = message.toString();
//				System.out.println("message:"+s);
//				Log.e("zxb-message", s);
				int index = s.indexOf("\"status\":\"ok\"");
				if(index!=-1){
					return "ok";
				}else{
					return "fail";
				}
				
			//	return message.toString();
			} catch (Exception e) {

//				System.out.println("*******message end error:*********" + e.getMessage());
				return null;
			}
		}
		return null;
	}

	public static byte[] convertUnicode2UTF8Byte(String s) {
		byte b[];
		byte b1[];
		int len;
		int count = 0;
		char c;
		if (s == null || s.length() == 0)
			return null;
		len = s.length();
		b = new byte[len * 3];
		for (int i = 0; i < len; i++) {
			c = s.charAt(i);
			if (0x0080 > c) {
				b[count++] = (byte) c;
			} else if (0x0800 > c) {
				b[count++] = (byte) ((c >> 6) | 0xc0);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			} else {
				b[count++] = (byte) ((c >> 12) | 0xE0);
				b[count++] = (byte) (((c & 0x0FC0) >> 6) | 0x80);
				b[count++] = (byte) ((c & 0x003F) | 0x80);
			}
		}
		b1 = new byte[count];
		System.arraycopy(b, 0, b1, 0, count);
		b = null;
		return b1;
	}

	private String getCookie(String cook){
		int site = cook.indexOf(";");
		if(site!=-1){
			cook = cook.substring(0,site);
		}
		return cook+"; ";
	}

	/**
	 * Method description
	 * 
	 */
	public static String convertByteArray2UTF8String(byte[] arrays) {
		if (arrays == null)
			return null;
		ByteArrayInputStream bais = new ByteArrayInputStream(arrays, 0,
				arrays.length);
		InputStreamReader isreader = null;

		try {
			isreader = new InputStreamReader(bais, "UTF-8");
		} catch (IOException ioe) {

		} catch (Exception exception1) {
			isreader = new InputStreamReader(bais);
		}
		String s;
		StringBuffer stringbuffer = new StringBuffer();
		int i = -1;
		do {
			try {
				if ((i = isreader.read()) == -1) {
					break;
				}
				char c = (char) i;
				if (c == '\n') {
					break;
				}
				if (c != '\r') {
					stringbuffer.append(c);
				}
				continue;
			} catch (IOException ioe) {

			} catch (Exception exception) {

			}
			break;
		} while (true);
		s = stringbuffer.toString();
		{
			try {
				if (isreader != null) {
					isreader.close();
					isreader = null;
				}
				if (bais != null) {
					bais.close();
					bais = null;
				}
			} catch (Exception exception3) {
			}
		}
		if (s.length() == 0) {
			if (i == -1) {
				return null;
			} else {
				return "";
			}
		} else {
			return s;
		}
	}

	private byte[] addCapacity(byte rece[]) {
		byte temp[] = new byte[rece.length + 1024];
		System.arraycopy(rece, 0, temp, 0, rece.length);
		return temp;
	}



}
